<template>
  <view class="flex-col" style="padding: 20rpx 20rpx 8rpx 20rpx">
    <view style="padding: 20rpx 20rpx 40rpx 20rpx; background-color: #fff"
          :class="form.invoiceType === 2 ? 'bottom115' : ''">
      <uni-forms ref="form" :model="form" labelWidth="auto" :rules="rules" :label-position="boole ? 'top' : 'left'">
        <uni-forms-item label="类型:" name="invoiceType" :required="boole" :rules="[
        {required: true,errorMessage: '请选择类型',validateTrigger: 'bind',}, ]">
          <view v-if="boole">
            <uni-data-checkbox @change="clearValidation" v-model="form.invoiceType"
                               :localdata="range"></uni-data-checkbox>
          </view>
          <text v-else>{{
              form.invoiceType === "1" ? "个人开票" : form.invoiceType === "2" ? "企业开票" : "" || "-"
            }}
          </text>
        </uni-forms-item>
        <uni-forms-item label="开票金额:" name="invoiceAmount" :required="boole">
          <uni-easyinput maxlength="12" v-model="form.invoiceAmount" v-if="boole" placeholder="请输入开票金额"/>
          <text v-else>{{ form.invoiceAmount || "-" }}</text>
        </uni-forms-item>
        <uni-forms-item label="发票类型:" name="invoiceCategory" :required="boole">
          <zxz-uni-data-select v-if="boole" v-model="form.invoiceCategory"
                               dataKey="label" dataValue="value"
                               :localdata="dict.type.invoice_type"/>
          <text v-else>{{
              handleLabel(dict.type.invoice_type, form.invoiceCategory) || "-"
            }}
          </text>
        </uni-forms-item>
        <uni-forms-item label="客户名称:" :required="boole" name="customerName">
          <uni-easyinput maxlength="50" v-model="form.customerName" v-if="boole" placeholder="请输入客户名称"/>
          <text v-else>{{ form.customerName || "-" }}</text>
        </uni-forms-item>
        <!--        <uni-forms-item v-if="form.invoiceType == 2" label="公司名称:" name="companyName" :required="boole">-->
        <!--          <uni-easyinput maxlength="50" v-model="form.companyName" v-if="boole" placeholder="请输入公司名称"/>-->
        <!--          <text v-else>{{ form.companyName || "-" }}</text>-->
        <!--        </uni-forms-item>-->
        <!--        <uni-forms-item v-if="form.invoiceType == 2" label="税号:" name="taxpayerIdentityNumber" :required="boole">-->
        <!--          <uni-easyinput maxlength="18" v-model="form.taxpayerIdentityNumber" v-if="boole" placeholder="请输入税号"/>-->
        <!--          <text v-else>{{ form.taxpayerIdentityNumber || "-" }}</text>-->
        <!--        </uni-forms-item>-->
        <uni-forms-item label="开户银行:" name="bankName" :required="boole">
          <uni-easyinput v-model="form.bankName" v-if="boole" placeholder="请输入开户银行"/>
          <text v-else>{{ form.bankName || "-" }}</text>
        </uni-forms-item>
        <uni-forms-item label="账户:" name="bankNumber" :required="boole">
          <uni-easyinput v-model="form.bankNumber" v-if="boole" placeholder="请输入账户"/>
          <text v-else>{{ form.bankNumber || "-" }}</text>
        </uni-forms-item>
        <uni-forms-item label="电子邮箱:" name="email">
          <uni-easyinput v-model="form.email" v-if="boole" placeholder="请输入电子邮箱"/>
          <text v-else>{{ form.email || "-" }}</text>
        </uni-forms-item>
        <uni-forms-item label="地址:" name="address">
          <uni-easyinput v-model="form.address" v-if="boole" placeholder="请输入地址"/>
          <text v-else>{{ form.address || "-" }}</text>
        </uni-forms-item>
        <uni-forms-item label="联系电话:" name="phone">
          <uni-easyinput v-model="form.phone" maxlength="11" v-if="boole" placeholder="请输入联系电话"/>
          <text v-else>{{ form.phone || "-" }}</text>
        </uni-forms-item>
        <uni-forms-item label="发票附件:" name="invoiceOss" required v-if="type == 'edit'">
          <image-common :disabled="false" :up-type="2" v-model="form.invoiceOss"/>
        </uni-forms-item>
        <uni-forms-item label="发票附件:" name="invoiceOss" :required="boole" v-if="type == 'detail'">
          <image-common :disabled="true" :up-type="2" v-model="form.invoiceOss"/>
        </uni-forms-item>
        <view style="height: 60rpx" />
      </uni-forms>
    </view>
    <view class="button-container" v-if="type !== 'detail'">
      <button class="btn-item" @click="submit">提 交</button>
    </view>
  </view>
</template>

<script>
import * as apis from "@/api/vehicleWarning";

export default {
  name: "makeOutInvoice",
  dicts: ["invoice_type"],
  onLoad(op) {
    let title = "";
    this.type = op?.type;
    if (op?.type === "add") {
      title = "申请发票";
      this.boole = true;
      this.requestUrl = apis?.applyInvoice
      let leasePurchaseTransferId = op?.leasePurchaseTransferId;
      this.$set(this.form, "leasePurchaseTransferId", leasePurchaseTransferId);
    }
    if (op?.type === "detail") {
      title = "查看发票";
      this.boole = false;
      this.getDetail(op?.invoiceId);
    }
    if (op?.type === "edit") {
      title = "开票";
      this.boole = false;
      this.getDetail(op?.invoiceId);
      this.requestUrl = apis?.invoicing
      this.$set(this.form, "leasePurchaseTransferId", leasePurchaseTransferId);
    }
    uni.setNavigationBarTitle({
      title,
    });
  },
  computed: {
    handleLabel() {
      return function (arr, type) {
        let name = "";
        arr.map((v) => {
          if (type == v.value) {
            name = v.label;
          }
        });
        return name;
      };
    },
  },
  onReady() {
    // 需要在onReady中设置规则
    this.$refs.form.setRules(this.rules);
  },
  data() {
    return {
      type: "",
      boole: false,
      form: {
        invoiceType: 1,
        invoiceAmount: "",
        invoiceCategory: "",
        customerName: "",
        bankName: "",
        bankNumber: "",
        email: "",
        address: "",
        phone: "",
        invoiceOss: "",
        leasePurchaseTransferId: null,
      },
      range: [
        {value: "1", text: "个人"},
        {value: "2", text: "企业"},
      ],
      rules: {
        invoiceAmount: {
          rules: [
            {
              required: true,
              errorMessage: "请输入开票金额",
            },
            {
              validateFunction: function (rule, value, data, callback) {
                const regex = /^(\d+\.?\d{0,2}|\.\d{1,2})$/;
                if (!regex.test(value)) {
                  callback("请输入正确的金额,正整数或0或者小数点后2位");
                }
                return true;
              },
            },
          ],
        },
        invoiceCategory: {
          rules: [
            {
              required: true,
              errorMessage: "请选择发票类型",
            },
          ],
        },
        customerName: {
          rules: [
            {
              required: true,
              errorMessage: "请输入客户名称",
            },
          ],
        },
        companyName: {
          rules: [
            {
              required: true,
              errorMessage: "请输入公司名称",
            },
          ],
        },
        bankName: {
          rules: [
            {
              required: true,
              errorMessage: "请输入开户银行",
            },
          ],
        },
        bankNumber: {
          rules: [
            {
              required: true,
              errorMessage: "请输入账户",
            },
            // {
            //   validateFunction: function (rule, value, data, callback) {
            //     const regex = /^\d{10,18}$/;
            //     if (!regex.test(value)) {
            //       callback("请输入正确账户");
            //     }
            //     return true;
            //   },
            // },
          ],
        },
        taxpayerIdentityNumber: {
          rules: [
            {
              required: true,
              errorMessage: "请输入税号",
            },
          ],
        },
        phone: {
          rules: [
            {
              validateFunction: function (rule, value, data, callback) {
                const regex = /^1[3-9]\d{9}$/;
                if (!regex.test(value)) {
                  callback("请输入正确手机号");
                }
                return true;
              },
            },
          ],
        },
        email: {
          rules: [
            {
              validateFunction: function (rule, value, data, callback) {
                const regex =
                    /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
                if (!regex.test(value)) {
                  callback("请输入正确邮箱");
                }
                return true;
              },
            },
          ],
        },
        invoiceOss: {
          rules: [
            {
              required: true,
              errorMessage: "请上传附件",
              validateTrigger: 'bind'
            },
          ],
        }
      },
      requestUrl: ''
    };
  },
  methods: {
    clearValidation() {
      this.$refs.form.clearValidate();
    },
    //查看发票详情接口
    async getDetail(id) {
      try {
        uni.showLoading();
        let res = await apis?.getInvoicing(id);
        this.form = res.data;
      } catch (error) {
        this.$nextTick(() => {
          uni.pageScrollTo({
            selector: error,
          });
        });
      } finally {
        uni.hideLoading();
      }
    },
    async submit() {
      try {
        let vaildResult = await this._validate()
        if (Array.isArray(vaildResult)) {
          return;
        }
        uni.showLoading();
        if (this.type === "add" || this.type === "edit") {
          const res = await this.requestUrl(this.form);
          let msg = this.type === "add" ? '申请开票' : this.type === "edit" ? '开票' : ''
          if (res.code === 200) {
            uni.$emit("refBackList", true);
            this.$modal.msgSuccess(`${msg}成功`);
            setTimeout(() => {
              this.$tab.navigateBack();
            }, 1000);
          }
        }
      } catch (error) {
        this.$nextTick(() => {
          uni.pageScrollTo({
            selector: error,
          });
        });
      } finally {
        uni.hideLoading();
      }
    },
  },
};
</script>

<style scoped lang="scss"></style>
